/**
 * @author Kidy.lv
 */
if (typeof DBHelper=='undefined') {
    DBHelper = {};
}
if(!DBHelper.get){
    DBHelper.get = function(url,data,callback,timeout){
        $.ajax({
            type:'GET',
            url:url,
            cache:false,
            timeout:timeout?timeout:null,
            data:$.param(data), 
            success:function(data){
                callback(data);
            },
            error:function(){
                callback("error");
            }
        });
    };
}
var QS_MarketSectorsManage = function(){
    var sectorMap={};
    var dataCache={};
    var intervalObj=null;
    var lock=false;
    var profile={
        pullTime:1,
        flashPoint: 'dChg%',
        getDataURL:(version.rtq||"../") + "invoke/sectorDelta",
        timeout:10
    };
    return {
        register:function(id,obj){
           sectorMap[id]=obj;
        },
        setInterval:function(){
            var self=this;
            if(intervalObj==null){
                this.getDataFromdCom();
                intervalObj= window.setInterval(function(){self.getDataFromdCom();},
                    profile.pullTime*60*1000);
            }
        },
        bindDataGrid:function(id){
            this.showSector(id);
            this.updateColor(id);
        },
        getDataFromdCom:function(){
            if(lock) return;
            lock = true;
            var self=this;
            DBHelper.get(profile.getDataURL,{},function(data){
                lock = false;
                var tag=false;
                if(data!=null&&$.trim(data)!=""){ 
                    var dataObj=$.evalJSON(data);
                    var ticker=null,needUpdateData={},tickerid=null,tickerData={};
                    for(var i=0,l=dataObj.length;i<l;i++){
                        needUpdateData={};
                        ticker = dataObj[i],tickerid=ticker.ticker,tickerData=ticker.data;
                        if(!dataCache[tickerid]){
                            tag=true;
                            dataCache[tickerid]={name:ticker.name,ticker:tickerid};
                            $.extend(true,dataCache[tickerid],tickerData);
                        }else{
                            if(typeof tickerData[profile.flashPoint]!='undefined'&&tickerData[profile.flashPoint]!=dataCache[tickerid][profile.flashPoint]){
                                needUpdateData[profile.flashPoint] = {"value":tickerData[profile.flashPoint],"ovalue":dataCache[tickerid][profile.flashPoint]};
                                $.extend(true,dataCache[tickerid],tickerData);
                                self.updateColor(dataCache);
                                self.updateData(tickerid,needUpdateData);
                            }
                        }
                    }
                    if(tag){
                        self.bindDataGrid();
                    }
                }
            },profile.timeout*1000);
        },
        unregister:function(id){
            delete sectorMap[id];
        },
        updateData:function(tid,needupdatedata){
            for(var sectorid in sectorMap){
                sectorMap[sectorid].updateData(tid,needupdatedata);
            }
        },
        updateSectorData:function(data){
            for(var sectorid in sectorMap){
                sectorMap[sectorid].updateSectorData(data);
            }
        },
        updateColor:function(id){
            if(typeof id != 'undefined'&&sectorMap[id]){
                sectorMap[id].updateColor(dataCache);
            }else{
                for(var sectorid in sectorMap){
                    sectorMap[sectorid].updateColor(dataCache);
                }
            }
        },
        showSector:function(id){
            if(typeof id != 'undefined'&&sectorMap[id]){
                sectorMap[id].showSector(dataCache);
            }else{
                for(var sectorid in sectorMap){
                    sectorMap[sectorid].showSector(dataCache);
                }
            }
        }
    };
}();
var QS_MarketSectors = function(){
	this.id = null;
    this.container = null;
    this.lastCallbackHeight=0;
    this.firstTag=true;
	this.staticValue={
		minWidth:220,
		realTime:"1d",
		defaultType:"mkt",
        winTitle:26
	};
    this.dataCache={};
    this.gridCache={};
	this.classMap={};
    this.cacheColor={};
    this._textKey = document.body.textContent ? 'textContent' : 'innerText';
	this.colorDomCache={};
    this.profile={
        isAPI:true,
        fixHeight:true,
    	type:"mkt",
        //https://rtqdev.morningstar.com/opt/invoke/sectorDelta?superTicker=F00000LJF6
        //https://rtqdev.morningstar.com/opt/invoke/sectorDelta?superTicker=F00000LJF6&subTicker=F00000LJ8T
    	currentDatapoint:"1d",
        rangeTitle: {'1d':'Day Change %', '1w':'1-Week Change %', '1m':'1-Month Change %', '3m':'3-Month Change %', '1y':'1-Year Change %', '3y':'3-Year Change %'},
        dataPoint: {'1d': 'dChg%', '1w': 'dpd005', '1m': 'dpd007', '3m': 'dpd009', '1y': 'dpd00d', '3y': 'dpd00f'},
        columns:[{
            header: "Symbols",
            dataIndex: 'Symbols',
            width: '80%',
            dataType: 'string'
        }, {
            header: "chg",
            dataIndex: 'dChg%',
            width: '20%',
            align: 'right',
            dataType: 'html'
        }],
        decimal:2,
        symbols:
        {
	        "mkt":{
	        	className:"sdmkt",
	        	colorTicker:"$MSTAR",
	            tickerList:["$MSTAR","F00000LJF6","F00000LJGX","F00000LJGV"]
	        },
	        "cyc":{
	        	className:"sdinfo",
	        	colorTicker:"F00000LJF6",
	            tickerList:["F00000LJF6","F00000LJ8T","F00000LJ8X","F00000LJ95","F00000LJ9B"]
	        },
	        "sen":{
	        	className:"sdservice",
	        	colorTicker:"F00000LJGX",
	            tickerList:["F00000LJGX","F00000LJ8V","F00000LJ91","F00000LJ99","F00000LJ9D"]
	        },
	        "def":{
	        	className:"sdmfg",
	        	colorTicker:"F00000LJGV",
	            tickerList:["F00000LJGV","F00000LJ8Z","F00000LJ97","F00000LJ9F"]
	        }
		}
	};
    this.callback={};
};
QS_MarketSectors.prototype = {
    init: function(containerId, profile, sId){
        this.container = $('#' + containerId);
        this.id = sId;
        QS_MarketSectorsManage.register(sId,this);
        $.extend(true,this.profile,profile);
        $.extend(true,this.callback,profile.callback||{});
		this._initDOM(this.container);
		this._createTickers();
		var self= this;
        if(this.profile.width){
            this.el.css({width:this.profile.width});
        }
        if(!this.profile.isAPI&&!isNaN(this.profile.height)){
            this.profile.height-=this.staticValue.winTitle;
        }
        this.scrollPanel = new Util.ScrollPanel(this.el.find(".qs-marketsectors-wap"),{showX:false,showY:this.profile.fixHeight});
        var self=this;
        QS_MarketSectorsManage.bindDataGrid(this.id);
        QS_MarketSectorsManage.setInterval();
    },
    clear:function(){
        QS_MarketSectorsManage.unregister(this.id);
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },
    saveConfig:function(){
        return null;
    },
    _createTickers:function(){
    	this.tickers=[],splice={};
    	for(var sector in this.profile.symbols){
    		this.classMap[this.profile.symbols[sector].className]=sector;
    		var tickers = this.profile.symbols[sector]["tickerList"];
    		for (var i = 0,l=tickers.length ; i <l; i++) {
                if(splice[tickers[i]]) continue;
                splice[tickers[i]]=true;
    			this.tickers.push(tickers[i]);
    		};
    	}
    },
    updateData: function(ticker,aData,needFlash){
    	if($.inArray(ticker, this.tickers)>=0){
			if(this.dtgrid && this.profile.currentDatapoint == this.staticValue.realTime){
                var field=this.profile.dataPoint[this.profile.currentDatapoint];
                if(aData[field]){
                    this._updateDOM(ticker, field, aData[field].value, aData[field].ovalue,needFlash);
                }
            } 
        }  
    },
    _updateDOM:function(gkey,gridField,value,oldvalue,needFlash){
        if (!this.dtgrid.DOMMap[gkey]) {
            return;
        }
        var el = this.dtgrid.DOMMap[gkey][gridField];
        if(!el) return;
        var _flashMethod = needFlash === false ? function(){}: flash,contentKey = this._textKey;
        _flashMethod(el,value,oldvalue);
        el[contentKey] = this._toDecimal(value);
    },
    _bindEvent: function(){
        var self = this;
        this.el.find('.main .qs-ui-triangle, .sub .qs-ui-triangle-sm').bind("mouseover",function(e){
        	var target=e.target;
        	if(target!=this){
                var pointClass=$(this).parent()[0].className.split(' '),
                typeClass=target.className.split(' ');
                self.profile.currentDatapoint = pointClass[0];
                self.profile.type = self.classMap[typeClass[0]];
                Util.DelayRun('mouseover.marketsectors',
                    function(){
                        self.showSector();
                    },100, self);
	        }
        }).bind("mouseleave",function(e){
        		self.profile.currentDatapoint =self.staticValue.realTime;
        		self.profile.type = self.staticValue.defaultType;
	            Util.DelayRun('mouseleave.marketsectors',
                    function(){
                        self.showSector();
                    },100, self);
	        }
        );
    },
    _initDOM:function(){
    	var html = '<div class="qs-marketsectors"><div class="qs-marketsectors-wap">'+
        '<div class="qs-triangle-container">' +
            '<div class="main clearfix">' +
                '<div class="1d box"><div class="qs-ui-triangle"><div class="sdservice l5"></div><div class="sdinfo l3"></div><div class="sdmfg l1"></div><div class="sdmkt l2"></div></div></div>' +
				'<div class="qs-triangle-txt defensive"></div><div class="qs-triangle-txt sensitive"></div><div class="qs-triangle-txt cyclical"></div><div class="qs-triangle-txt mkt"></div>'+
            '</div>' +
            '<div class="sub clearfix">' +
                '<div class="1w box"><div class="qs-ui-triangle-sm"><div class="sdservice l5"></div><div class="sdinfo l3"></div><div class="sdmfg l1"></div><div class="sdmkt l2"></div></div></div>' +
                '<div class="1m box"><div class="qs-ui-triangle-sm"><div class="sdservice l1"></div><div class="sdinfo l2"></div><div class="sdmfg l3"></div><div class="sdmkt l4"></div></div></div>' +
                '<div class="3m box"><div class="qs-ui-triangle-sm"><div class="sdservice l1"></div><div class="sdinfo l7"></div><div class="sdmfg l5"></div><div class="sdmkt l4"></div></div></div>' +
                '<div class="1y box"><div class="qs-ui-triangle-sm"><div class="sdservice l3"></div><div class="sdinfo l7"></div><div class="sdmfg l2"></div><div class="sdmkt l4"></div></div></div>' +
                '<div class="3y box"><div class="qs-ui-triangle-sm"><div class="sdservice l1"></div><div class="sdinfo l6"></div><div class="sdmfg l2"></div><div class="sdmkt l4"></div></div></div>' +
            '</div>' +
            '<div class="subTitle">' +
                '<div class="title">1Wk</div>' +
                '<div class="title">1Mo</div>' +
                '<div class="title">3Mo</div>' +
                '<div class="title">1Yr</div>' +
                '<div class="title">3Yr</div>' +
            '</div>' +
        '</div>' + 
        '<div class="qs-marketsectors-grid">' + 
            '<div class="title"><h3>Morningstar Indexes</h3></div>' + 
            '<div class="range">Day Change %</div>' + 
            '<div class="dtgrid"></div>' + 
        '</div></div></div>';
     	this.el = $(html);
    	this.el.appendTo(this.container);
    	this.$rangeTitle=this.el.find('.range');
    	this._initDTGrid();
    	this._bindEvent();
    },
    showSector:function(dataCache){
    	this._changeRangTitle(this.profile.currentDatapoint);
        if(!$.isEmptyObject(dataCache)){
            this.dataCache=dataCache;
        }
        if(!$.isEmptyObject(this.dataCache)){
            this.dtgrid.reBindData(this._getData(this.profile.type, this.profile.currentDatapoint));
        }
    },
    _changeRangTitle:function(datapoint){
    	this.$rangeTitle.html(this.profile.rangeTitle[datapoint]);
    },
    _getData:function(type,datapoint){
    	if(!this.gridCache[type]) this.gridCache[type]={};
    	if(!this.gridCache[type][datapoint]) {
    		this.gridCache[type][datapoint]=[];
    	}else if(datapoint!=this.staticValue.realTime){
    		return this.gridCache[type][datapoint];
    	}
        this.gridCache[type][datapoint]=[];
    	var tickerlist=this.profile.symbols[type]["tickerList"];
    	var dataPoint=this.profile.dataPoint[datapoint],itemdata={};
		for (var i = 0,l=tickerlist.length ; i <l; i++) {
            itemdata={};
            itemdata["rowid"]=tickerlist[i];
            itemdata["Symbols"]=this.dataCache[tickerlist[i]]["name"];
            itemdata[this.profile.dataPoint[this.staticValue.realTime]]=this._toDecimal(this.dataCache[tickerlist[i]][dataPoint]);
            this.gridCache[type][datapoint].push(itemdata);
		};
		return this.gridCache[type][datapoint];
    },
    _getChgs:function(type){
    	var data={},colorDom={};
    	if(!this.colorDomCache[type]) this.colorDomCache[type]={};
    	var tickers=this.profile.symbols[type]["colorTicker"],boundary=0;
    	for(var datapoint in this.profile.dataPoint){
    		if(datapoint!=this.staticValue.realTime){
    			if(!this.colorDomCache[type][datapoint]){
    				this.colorDomCache[type][datapoint]=this.el.find('.'+datapoint+' .qs-ui-triangle-sm').find('.'+this.profile.symbols[type].className);
    			}
    		}else{
    			if(!this.colorDomCache[type][datapoint]){
    				this.colorDomCache[type][datapoint]=this.el.find('.'+datapoint+' .qs-ui-triangle').find('.'+this.profile.symbols[type].className);
    			}
    		}
    		data[datapoint]=this._toDecimal(this.dataCache[tickers][this.profile.dataPoint[datapoint]]);
    		boundary=Math.max(Math.abs(data[datapoint]),boundary);
    	}
    	return {data:data,boundary:boundary};
    },
    _toDecimal:function(data){
    	if(isNaN(data)) return "0.00";
    	return parseFloat(parseFloat(data).toFixed(this.profile.decimal));
    },
    _initDTGrid:function(){
    	var self=this;
    	var columns=[{
                header: "rowid",
                dataIndex: 'rowid',
                width: 0,
                dataType: 'string',
                hide: true
            }].concat(this.profile.columns);
    	this.dtgrid = new Util.DataGrid(this.el.find('.qs-marketsectors-grid .dtgrid'), [], {
            column: columns,
            autoWidth: true,
			autoHeight: true,
            htmlLayer: 'div',
            headerRow: false,
            sortable: false,
            cellRearrange: false,
            rowDragable: false,
            rowDropable: false
        }, {
        	afterRebindData: function(DOMMap, rows){
                if(self.profile.isAPI){
                    self.changeOutSize(self.el.width(),self.el.height());
                }else{
                    self.changeOutSize();
                }
        		if (self.firstTag) {
		            Util.DelayRun('onload.marketSectors', self.loadHandler, 100, self);
		        }else {
		            Util.DelayRun('heightchange.marketSectors', self.heightChangeHandler, 100, self);
		        }
	        }
	    });
    },
    _calcColorScope:function(type,datapoint,value,boundary){
        //l1 green - > l7 red
        var colorindex="l4";
        switch(datapoint){
            case "1d":
            case "1w":
                if(value<-1.25){
                    colorindex="l7";
                }else if(value>=-1.25&&value<-0.5){
                    colorindex="l6";
                }else if(value>=-0.5&&value<0.0){
                    colorindex="l5";
                }else if(value==0.0){
                    colorindex="l4";
                }else if(value>0.0&&value<=0.5){
                    colorindex="l3";
                }else if(value>0.5&&value<=1.25){
                    colorindex="l2";
                }else if(value>1.25){
                    colorindex="l1";
                }
                break;
                //'1d': 'dChg%', '1w': 'dpd005', '1m': 'dpd007', '3m': 'dpd009', '1y': 'dpd00d', '3y': 'dpd00f'},
            case "1m":
                if(value<-4.0){
                    colorindex="l7";
                }else if(value>=-4.0&&value<-2.0){
                    colorindex="l6";
                }else if(value>=-2.0&&value<0.0){
                    colorindex="l5";
                }else if(value==0.0){
                    colorindex="l4";
                }else if(value>0.0&&value<=2.0){
                    colorindex="l3";
                }else if(value>2.0&&value<=4.0){
                    colorindex="l2";
                }else if(value>4.0){
                    colorindex="l1";
                }
                break;
            case "3m":
                if(value<-8.0){
                    colorindex="l7";
                }else if(value>=-8.0&&value<-4.0){
                    colorindex="l6";
                }else if(value>=-4.0&&value<0.0){
                    colorindex="l5";
                }else if(value==0.0){
                    colorindex="l4";
                }else if(value>0.0&&value<=4.0){
                    colorindex="l3";
                }else if(value>4.0&&value<=8.0){
                    colorindex="l2";
                }else if(value>8.0){
                    colorindex="l1";
                }
                break;
            case "1y":
            case "3y":
                if(value<-20.0){
                    colorindex="l7";
                }else if(value>=-20.0&&value<-10.0){
                    colorindex="l6";
                }else if(value>=-10.0&&value<0.0){
                    colorindex="l5";
                }else if(value==0.0){
                    colorindex="l4";
                }else if(value>0.0&&value<=10.0){
                    colorindex="l3";
                }else if(value>10.0&&value<=20.0){
                    colorindex="l2";
                }else if(value>20.0){
                    colorindex="l1";
                }
                break;
            default:
                break
        }
        return colorindex;
    },
    updateColor: function(dataCache){
        if($.isEmptyObject(dataCache)) return;
        this.dataCache=dataCache;
        var self = this,chgs={};
        for(var type in this.profile.symbols){
        	var dom=null,colorindex=null,className=null;
        	chgs=this._getChgs(type);
            if(!this.cacheColor[type]) this.cacheColor[type]={};
        	for(var datapoint in chgs.data){
                colorindex= this._calcColorScope(type,datapoint,chgs.data[datapoint],chgs.boundary);
                if(this.cacheColor[type][datapoint] != colorindex){
                    this.cacheColor[type][datapoint] = colorindex;
                    className=this.colorDomCache[type][datapoint].get(0).className||"";
                    this.colorDomCache[type][datapoint].removeClass(className);
                    className = className.replace(/l[\d]$/, colorindex);
                    this.colorDomCache[type][datapoint].addClass(className);
                }
        	}
        }
    },
    changeOutSize: function(w, h){
        if(this.profile.isAPI){
            w = this.profile.width||w||this.container.width();
            h = this.profile.height||h||this.container.height();
        }else{
            //if it is terminal, the height of win-bd is static
            w = w||this.container.parent().width();
            h = h||this.container.parent().height();
            this.el.css({
                width: "auto"
            });
        }
        if(this.profile.fixHeight){
            this.scrollPanel.reSize(w, h);
        }else{
            this.scrollPanel.reSize(w, null);
            h = this.el.height();
        }
    },
    loadHandler:function(){
		var height = this.el.height() + 21;
        this.firstTag = false;
        this.lastCallbackHeight = height;
        if (typeof this.callback.onLoad == 'function') {
			this.callback.onLoad({
				component: 'marketSectors',
				height: height,
				minWidth: this.staticValue.minWidth
			});
		}
    },
    heightChangeHandler:function(){
        var height = this.el.height() + 21;
        if (this.lastCallbackHeight != height) {
            this.lastCallbackHeight = height;
            if (typeof this.callback.onHeightChange == 'function') {
               this.callback.onHeightChange({
            		height: height,
            		component: 'marketSectors',
            		minWidth: this.staticValue.minWidth
               });
           }
        }
	}
}